package com.eryos.android.cigarettecounter.ui;

import java.io.IOException;
import java.net.UnknownHostException;

import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.eryos.android.cigarettecounter.R;
import com.eryos.android.cigarettecounter.charts.Chart;
import com.eryos.android.cigarettecounter.tool.GoogleAnalyticsProvider;

/**
 * Project : CigaretteCounter Author : Olivier Combe URL : http://eryos.fr/CigaretteCounter/
 * 
 * Copyright(C)2011 - Olivier Combe
 * 
 * Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 * 
 * @version \$Revision.*\$
 * @author Olivier Combe
 */
public class ChartPopup extends Dialog {

    /** Logger label. */
    private static final String LOG_TAG = "ChartPopup";
    private Context context;

    /* UI Elements */
    private ImageView chartFullScreen;
    private Button shareButton;
    private Chart chart;
    private Bitmap bmp;

    /**
     * Create a new popup with param defined chart.
     * 
     * @param contextArg
     *            of the application
     * @param chartArg
     *            to display
     */
    public ChartPopup(final Context contextArg, final Chart chartArg) {
        super(contextArg);
        Log.w(LOG_TAG, getClass().getSimpleName() + " : new ChartPopup()");

        /* Define & Initialize attributes */
        this.context = contextArg;
        this.setChart(chartArg);
        this.setContentView(R.layout.chart_dialog);
        this.setTitle(chartArg.getTitle());

        /* Retrieve UI Components */
        chartFullScreen = (ImageView) findViewById(R.id.popup_image);
        shareButton = (Button) findViewById(R.id.popup_share_button);
        shareButton.setEnabled(false);

        /* Download chart from Google API */
        new DownloadFilesTask().execute(chartArg.getURL());

        /* Show Popup */
        this.show();

        /* Listener for closing Popup */
        chartFullScreen.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(final View v, final MotionEvent event) {
                dismiss();
                return false;
            }
        });

        /* Listener for Share button */
        shareButton.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(final View v, final MotionEvent e) {
                if (e.getAction() == MotionEvent.ACTION_DOWN) {
                    Log.d("Popup", "Click");
                    shareGraphic();
                }
                return true;
            }
        });
    }

    /**
     * Save the current bitmap on SDCard, et raise an intent to share the picture.
     */
    public void shareGraphic() {
        Log.w(LOG_TAG, "shareGraphic");

        /* Create new ACTION_SEND intent */
        Intent shareIntent = new Intent(Intent.ACTION_SEND);

        /* Define type of content */
        shareIntent.setType("image/jpeg");
        shareIntent.setFlags(0x1/* Intent.FLAG_ACTIVITY_NEW_TASK */);
        shareIntent
                .setComponent(ComponentName
                        .unflattenFromString("com.google.android.apps.plus/com.google.android.apps.plusone.app.ComposeUpdateActivity"));

        /* Write image to file on SD Card */
        String uri = Chart.writeBitmapToSD(bmp, chart.getTitle().replaceAll(" ", "_"));

        /* Attach Title/Text/Subjet to Intent */
        shareIntent.putExtra(Intent.EXTRA_TITLE, "Here's my smoking stats ...(generated from CigaretteCounter)");
        shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Here's my smoking stats ...(generated from CigaretteCounter)");
        shareIntent.putExtra(Intent.EXTRA_TEXT, "Here's my smoking stats ...(generated from CigaretteCounter)");

        /* Attach file(with URI)to Intent */
        Uri attachedFile = Uri.parse("file://" + uri);
        shareIntent.putExtra(Intent.EXTRA_STREAM, attachedFile);

        /* Track Google Analytics Event */
        GoogleAnalyticsProvider.trackEvent("Share", "Chart");

        /* Raise Intent */
        context.startActivity(Intent.createChooser(shareIntent, "Choose an appli to send your chart"));
    }

    /**
     * Return chart defined for the popup.
     * 
     * @return current chart
     */
    public Chart getChart() {
        return chart;
    }

    /**
     * Change the chart of the popup.
     * 
     * @param chartArg
     *            to use
     */
    public final void setChart(final Chart chartArg) {
        this.chart = chartArg;
    }

    // ######################################################################## //
    // ######################################################################## //
    // ######################################################################## //

    /**
     * Background task used to download chart and convert to bitmap.
     */
    private class DownloadFilesTask extends AsyncTask<String, Integer, Bitmap> {

        private final Bitmap errorBitmap = null;

        /**
         * {@inheritDoc} Step 1 - invoked on the UI thread immediately after the task is executed. This step is normally
         * used to setup the task, for instance by showing a progress bar in the user interface
         */
        @Override
        protected void onPreExecute() {
            chartFullScreen.setImageDrawable(context.getResources().getDrawable(R.drawable.loader/* .eryos */));
        }

        /**
         * {@inheritDoc} Step 2 - invoked on the background thread immediately after onPreExecute()finishes executing.
         * This step is used to perform background computation that can take a long time
         */
        @Override
        protected Bitmap doInBackground(final String... urls) {

            try {
                bmp = Chart.downloadChartAsBitmap(context, urls[0]);
                return bmp;
            } catch (UnknownHostException e) {
                return errorBitmap;
            } catch (IOException e) {
                Log.e(getClass().getSimpleName(), "doInBackground Error ", e);
                return errorBitmap;
            }

        }

        /**
         * {@inheritDoc} Step 3 - invoked on the UI thread after the background computation finishes. The result of the
         * background computation is passed to this step as a parameter.
         */
        @Override
        protected void onPostExecute(final Bitmap result) {
            if (result != null) {
                chartFullScreen.setImageBitmap(result);
                shareButton.setEnabled(true);
                Toast.makeText(context, "download OK", Toast.LENGTH_SHORT).show();
            } else {
                chartFullScreen.setImageDrawable(context.getResources().getDrawable(R.drawable.eryos)); // TODO change
                                                                                                        // bitmap
                Toast.makeText(context, "Sorry, an error occurs while downloading chart", Toast.LENGTH_LONG).show();
            }
        }
    }
}
